#!/usr/bin/env bash

set -e

function usage(){
    echo "运行脚本后续跟模块名称，可以联系多个模块，当发现不是模块名的参数时，后续所有参数作为额外参数输入"
    echo "例子：bash runmonitor.sh dl2 cl2 dl4 cl4 -t 3"
    echo "已定义的模块名：localserver dl2 cl2 dl4 cl2 pl2 pl4 can gps screen "
    echo "如果需要查看的模块不再已定义的范围内，请直接输入端口号"
}

declare -A port_map
port_map["localserver"]="12346"
port_map["dl2"]="15343"
port_map["dl4"]="15344"
port_map["cl2"]="15345"
port_map["cl4"]="15346"
port_map["pl2"]="14444"
port_map["pl4"]="14445"
port_map["can"]="15976"
port_map["gps"]="15975"
port_map["screen"]="43210"

if [ $# -eq 0 ]; then
    usage
    exit 1
fi

case $1 in
-h | --help)
    usage
    exit 0
    ;;
esac

command="/opt/app/aiforce/lib/msg_monitor -a"

found_non_module=false

for arg in "$@"; do
    if [ "$found_non_module" = false ]; then
        if [[ -n "${port_map[$arg]}" ]]; then
            command="$command localhost:${port_map[$arg]}"
        else
            found_non_module=true
            command="$command $arg"
        fi
    else
        command="$command $arg"
    fi
done

echo "command line: $command"
eval $command

trap 'echo "Terminated by user input"; exit 1' SIGINT